package com.boful.convert.core.impl;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

import com.boful.common.file.utils.FileUtils;
import com.boful.convert.core.TranscodeEvent;
import com.boful.convert.model.DiskFile;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

public class DocConvert {
	private String sofficePath;
	private static Logger logger = Logger.getLogger(DocConvert.class);

	public String getSofficePath() {
		return sofficePath;
	}

	public void setSofficePath(String sofficePath) {
		this.sofficePath = sofficePath;
	}

	public DocConvert(String sofficePath) {
		this.sofficePath = sofficePath;
	}

	public synchronized void convert(DiskFile srcFile, DiskFile destFile,
			TranscodeEvent event, String jobId) {
		if(srcFile.getFileType().equalsIgnoreCase("txt")){
			try{
				txtToPdf(srcFile, destFile);
				if(event!=null){
					event.onTranscodeSuccess(srcFile, destFile, jobId);
				}
			}catch(Exception e){
				if(event!=null){
					event.onTranscodeFail(srcFile, e.getMessage(), jobId);
				}
			}
			return;
		}
		System.out.println("soffice path:" + getSofficePath());
		StringBuffer cmd = new StringBuffer(getSofficePath());
		cmd.append("  --headless --convert-to pdf  ");
		cmd.append(srcFile.getAbsolutePath());
		Runtime runtime = Runtime.getRuntime();
		try {
			event.onStartTranscode(srcFile, jobId);
			logger.debug("转换文档命令行:" + cmd);
			System.out.println("转换文档命令行:" + cmd);
			Process process = runtime.exec(cmd.toString());
			process.waitFor();
			if (process.exitValue() == 0) {
				File file = new File(".", srcFile.getFileName() + ".pdf");
				if (!file.exists()) {
					event.onTranscodeFail(srcFile, "命令运行不成功！", jobId);
				} else {
					FileUtils.copyFile(file, destFile);
					event.onTranscodeSuccess(srcFile, destFile, jobId);
					file.delete();
				}
			} else {
				event.onTranscodeFail(srcFile, cmd + "命令运行不成功！", jobId);
			}
		} catch (IOException | InterruptedException e) {
			logger.error(e);
			event.onTranscodeFail(srcFile, e.getMessage(), jobId);
		}
	}

	public static void main(String[] args) {
		DiskFile srcFile = new DiskFile("/home/ligson/workspace/demo.doc");
		DiskFile destFile = new DiskFile("/home/ligson/demo.pdf");
		DocConvert docConvert = new DocConvert("/usr/bin/X11/unoconv");
		docConvert.convert(srcFile, destFile, new TranscodeEvent() {

			@Override
			public void onTranscodeSuccess(DiskFile diskFile,
					DiskFile destFile, String jobId) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTranscodeFail(DiskFile diskFile, String errorMessage,
					String jobId) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTranscode(DiskFile diskFile, int process, String jobId) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSubmitSuccess(DiskFile diskFile, String jobId) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSubmitFail(DiskFile diskFile, String errorMessage,
					String jobId) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTranscode(DiskFile diskFile, String jobId) {
				// TODO Auto-generated method stub

			}
		}, null);
	}

	/***
	 * 文本文件转pdf
	 * 
	 * @param src
	 *            文本文件
	 * @param dest
	 *            目标pdf文件
	 * @throws Exception
	 *             异常
	 */
	public static void txtToPdf(File src, File dest) throws Exception {

		Document document = new Document(PageSize.A4);
		BufferedReader reader = null;
		try {
			FileOutputStream fos = new FileOutputStream(dest);
			PdfWriter writer = PdfWriter.getInstance(document, fos);
			document.open();
			StringBuffer sb = new StringBuffer();
			String encode = FileUtils.getFileEncode(src);
			encode = encode==null?"GBK":encode;
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(src),encode));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\n\r");
			}
			System.out.println(sb.toString());
			BaseFont bfChinese = BaseFont.createFont("STSong-Light",
					"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			Font chineseFont = new Font(bfChinese, 12, Font.NORMAL);
			document.add(new Paragraph(sb.toString(), chineseFont));
		} catch (IOException | DocumentException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} finally {
			document.close();
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
